var service = new EbeimService();
$(function(){
	$W = $(window).width();
	$H = $(window).height();
	w = $(".window").width(); 
	h = $(".window").height();
	$(".window").css("top",(($H-h)/2)-80);
	$(".window").css("left",($W-w)/2);
	setInterval("getDownloadProcessBar()", 2500);
	setInterval("getUploadProcessBarAll()", 2500);
	$("#delefile").click(function(){
		if($(this)[0].checked){
			$(".del-class").css("display","table-row");
		}else{
			$(".del-class").css("display","none");
		}
	});
	
});

function importFunc(){
	$("#h_whichGetModel").val("importDs");
	selectSafeboxPath("");
}

function importDs(){
	var abDir = $("#ab-dir").html();
	if (abDir == "") {
		plugin.msgtip({type: "e", msg: "请选择路径！"});
		return;
	}
	var s_path = abDir;
	
	var name = s_path;
	var idx = s_path.lastIndexOf("/");
	if(idx == s_path.length-1){
		s_path = s_path.substring(0,idx);
	}
	idx = s_path.lastIndexOf("/");
	if(idx != -1){
		name = s_path.substring(idx+1,s_path.length);
	}
	var ds = {
		name : name,
		dsType : 2,
		isOpenLocalBackup : 0,
		dsSecurityRank : 0,
	};
	var bs = {
		type : 2,
		backupTime : 0,
		backupCycle : 1,
		backupPeriod : 1,
	}
	var config = {
		isEncrypt:1,
		root : abDir,
	}
	var bean = {
		dsId:$dsId,
		version:$version,
		path:$path
	}
	var json = {};
	json["datasource"] = ds;
	json["datasourceConfig"] = config;
	json["backStrategy"] = bs;
	json["bean"] = bean;
	$("#confirmBtn").css("color","gray");
	service.importDs(json, function(data){
		clearDateAndWindow();
		var v = data.version + ".0";
		$version = v;
		initTree(true);
		getVersionTree($dsId, $path, $version, $root, 1);
	});
//	service.addDataSource(json, importDsCB);
};
var importDsCB = function(data){
	clearDateAndWindow();
	var json = data;
	if (json.code == 200 || json.code == "200") {
		plugin.msgtip({type: "o", msg: "导入成功!即将进行上传!"});
		handBackup(json.dsId, 0);
		setTimeout(function(){
			getDateSoucesByPage();
		}, 1000);
	} else {
		dsSecurityRankCheck(json,json.message);
	}
}

function deleteUploadBar(dsId){
	if(!dsId){
		dsId = "";
		$(".delUploadBtn").each(function(){
			dsId += $(this).attr("id")+",";
		});
		if(dsId.length>0){
			dsId = dsId.substring(0,dsId.length-1);
		}
	}
	if(!dsId || dsId.length==0){
		plugin.msgtip({type:"e",msg:"还没可以清除的数据!"});
		return;
	}
	service.deleteUploadProcessBar(
		{
			dsIds:dsId
		},
		function(data){
			
		}
	);
}

function getUploadProcessBarAll(){
	service.getUploadProcessBarAll({}, function(data){
		var beans = data.beans;
		var uploadProcessbarContent = "";
		if(beans.length > 0){
			$("#upload_process_tag").css("display","block");
			$("#upload_process_tag").html(beans.length);
		}else{
			$("#upload_process_tag").css("display","none");
		}
		for(var i = 0; i<beans.length; i++){
			var bean = beans[i];
			var fs = bean.fileSum - (bean.okSum + bean.errorSum);
			var p = Math.floor((bean.count * 100 / bean.total)*100)/100;
			var info = "";
			var btn = "";
			if(p == 0 && fs>0){
				info="正在加密中..."
			}else if(p == 0 && fs<=0){
				info="上传失败!"
			}else if(p >= 100 || fs<=0){
				info = "上传完成!";
				p = 100;
				btn = "<a class='delUploadBtn' id='"+bean.dsId+"' href='javascript:deleteUploadBar(\""+bean.dsId+"\");'>删除</a>";
			}else{
				info = "上传进度:"+ p + "%";
			}
			uploadProcessbarContent = uploadProcessbarContent
			+"<tr>"
			+"	<td><nobr style='max-width:200px;display:inline-block;overflow:hidden;text-overflow:ellipsis;'>"+bean.name+"</nobr></td>"
			+"	<td width='150px' style='text-align:center;' dsid='"+bean.id+"' class='processTD'>"
			
			+"<div class='processbar' style='background:#ddd;width:100px;height:20px;position:relative;margin:0 auto;'>"
			+ "<div class='bar' style='height:20px;background:green;width:"+p+"%;'></div>"
			+ "<div class='info' style='font-size:10px;width:100px;height:20px;color:#fff;position:absolute;top:0;left:0'>"
			+	info
			+" </div>"
			+"</div>"
			
			+"</td>"
			+"	<td width='60px;' style='text-align:center;'>"+btn+"</td>"
			+"</tr>";
		}
		$("#uploadProcessbarTB").html(uploadProcessbarContent);
	});
}

function showUploadBar(){
	showDialog('uploadWindow');
}
var getVersionTreeCB = function (data) {
    var json = data;
    var str = '';
    for (i = 0; i < json.length; i++) {
        var f = json[i];
        var path = f.path.split("\\\\").join('\\');
        path = path.split("\\").join('\\\\');
        var fileSize = "-";
        var icon = "";
        var status = f.status;
        if(status == "删除"){
        	
            if(f.type == "文件"){
            	fileSize = fileSizeTransfer(f.fileSize);
            	icon = "<a href='javascript:;'><i class='inline-block folder-icon folder-dele-file'></i></a>";
            }else{
            	icon = "<a href='javascript:getVersionTree(\""+$dsId+"\",\""+path+"\",\""+$version+"\");'><i class='inline-block folder-icon folder-dele-folder'></i></a>";
            }
        	status = "<font color='red'>删除</font>";
        	str+="<tr class='del-class'>";
        	
        }else{
        	
        	if(f.type == "文件"){
            	fileSize = fileSizeTransfer(f.fileSize);
            	icon = "<a href='javascript:;'><i class='inline-block folder-icon folder-file'></i></a>";
            }else{
            	icon = "<a href='javascript:getVersionTree(\""+$dsId+"\",\""+path+"\",\""+$version+"\");'><i class='inline-block folder-icon folder-folder'></i></a>";
            }
        	str+="<tr>";
        }
        str+="	<td width='93'>"+icon+"</td>"
		+"	<td width='157' class='g-al'><input class='inp-name' type='text' value='"+f.name+"' readonly='readonly' style='width:153px'></td>"
		+"	<td width='93'>"+status+"</td>"
		+"	<td width='92'>文件夹</td>"
		+"	<td width='111'>"+fileSize+"</td>"
		//+"	<td width='15%' class='g-al'><span class='tipspan'></span></td>";
		if(f.status=="失败"){
			str += "<td width='204' nid='"+f.nid+"' class='bartd' id='bartd"+i+"'>&nbsp;</td>";
		}else if(f.type == "文件夹"){
         	str += "<td width='204' nid='"+f.nid+"' class='bartd' id='bartd"+i+"'><button class='folder-table-btn c02' onclick='directors(\""+$dsId+"\",\""+path+"\",\""+$version+"\",\""+f.name+"\",\"bartd"+i+"\",\""+f.nid+"\")'>数据恢复</button></td>";
         }else{
         	str += "<td width='204' nid='"+f.nid+"' class='bartd' id='bartd"+i+"'><button class='folder-table-btn c02' onclick='files(\""+$dsId+"\",\""+path+"\",\""+$version+"\",\""+f.name+"\",\"bartd"+i+"\",\""+f.nid+"\")'>数据恢复</button></td>";
         }
		str += "</tr>";

    }
    $("#tbody").html(str);
	if($("#delefile")[0].checked){
		$(".del-class").css("display","table-row");
	}else{
		$(".del-class").css("display","none");
	}
    getDownloadProcessBar();
    getUploadProcessBarAll();
};
var $dsId,$version,$path="/",$parent="",$root="";
function getVersionTree(dsId,path,version,root,currentVersionMajor){
	$("#confirmBtn").css("color","#fff");
	if(currentVersionMajor == 0){
		plugin.msgtip({type: "e", msg: "该数据还没有备份过！"});
		return;
	}
	if(root){
		$root = root;
	}else if(path==""){
		$root = "\\";
	}
	if(path!=""){
		var idx = path.lastIndexOf("\\");
		if(idx!=-1){
			$parent = path.substring(0,idx);
			var idx2 = $parent.lastIndexOf("\\");
			if(idx2==-1){
				$parent = "\\";
			}
		}
	}
	$('#currentPath').html($root+path);
	
	$dsId = dsId;
	$version = version;
	$path = path;
	service.getFileList({
		dsId:dsId,
		version:version,
		path:encodeURIComponent(path)
	}, getVersionTreeCB);
}
function parentNode(){
	var path = $parent;
	if(path==""){
//		service.getDataSourcesByPage({
//			offset:0,
//			pagesize:10000,
//			dsType:"2",
//			status:"",
//			name:""
//		}, dsCB);
		getVersionTree($dsId,"",$version);
	}else if(path=="\\"){
		$parent = "";
		getVersionTree($dsId,"",$version);
	}else{
		getVersionTree($dsId,path,$version);
	}
}

function directors(dsId,path,version,name,bartd_id,nid){
	$("#h_dsId").val(dsId);
	$("#h_path").val(path);
	$("#h_bartd_id").val(bartd_id);
	$("#h_version").val(version);
	if(nid){
		$("#h_nid").val(nid);
	}
	service.getBackuplogs(getBackupWrapper(dsId), backupLogCB);
	
}
function files(dsId,path,version,name,bartd_id,nid){
	$("#h_dsId").val(dsId);
	$("#h_bartd_id").val(bartd_id);
	$("#h_path").val(path+"\\"+name);
	if(nid){
		$("#h_nid").val(nid);
	}
	var service1 = new EbeimService();
	service1.getFileChangeLog({
		dsId:dsId,
		path:encodeURIComponent(path),
		version:version,
		name:encodeURIComponent(name)
	}, fileChangeLogBC);
}

var fileChangeLogBC = function (data) {
    var json = eval("(" + data + ")");
	var list = json.list.objList;
	
	var content = "";
	for (var i = 0; i < (list.length>5?5:list.length); i++) {
		var obj = list[i];
		content = content
		+"<li>"
		+"<span style='float:left;'><button onclick='recoveryClick(\""+obj.version+"\",\""+obj.datasourceId+"\")' class='btn'>恢复至</button></span>"
		+"<span style='float:right;'>"+getTimeStr(obj.logTime)+"</span>"
		+"</li>";
	}
	$(".filechangelog-ul").html(content);
	showDialog("versionWindow");
	
};

function getBackupWrapper(dsId) {
	var version = $("#h_version").val();
	if(version!=""){
		version = version.substring(0,version.indexOf("."));
	}
	var backupLog = {
		dsId : dsId,
		versionMajor:version,
		status:0
	}
	var pages = {
		startPos : 0,
		pageSize : 5
	}
	var bean = {
		path:$("#h_path").val()
	}
	var json = {};
	json["backupLog"] = backupLog;
	json["pages"] = pages;
	json["bean"] = bean;

	return json;
}

function recoveryClick(version,dsId,isRoot){
	$("#h_whichGetModel").val("recovery");
	$("#h_version").val(version);
	$("#h_dsId").val(dsId);
	if(isRoot==true){
		$("#h_path").val("/");
	}
	selectRecoveryPath("","recovery");
}

var backupLogCB = function(data){
	var list = data.list.objList;
	var size = list.length;
	var content = "";
	for (var i = 0; i < size; i++) {
		obj = list[i];
		content = content
		+"<li>" 
		+"<span style='float:left;'><button onclick='recoveryClick(\""+obj.versionMajor+".0\",\""+obj.dsId+"\","+data.isRoot+")' class='btn'>恢复至</button></span>"
		+"<span style='float:right;'>"+getTimeStr(obj.beginTime)+"</span>"
		+"</li>";
	}
	if(size==0){
		content = content
		+"<li style='text-align:center'>暂无可恢复的版本!</li>";
	}
	$(".filechangelog-ul").html(content);
	showDialog("versionWindow");
};
function selectRecoveryPath(path,recovery){
	$(".window").css("display","block");
	$(".shadowDiv").css("display","block");
	var abDir = $("#ab-dir").html();
	if(abDir!=""){
		$("#ab-dir").html(abDir+"\\"+path);
		service.getSystemDirs({
			path:abDir+"\\"+path,
			action:recovery
		}, function(data){
			selectPathCB(data,recovery);
		});
	}else{
		$("#ab-dir").html(path);
		service.getSystemDirs({
			path:path,
			action:recovery
		}, function(data){
			selectPathCB(data,recovery);
		});
	}
}
var selectPathCB = function(data,recovery){
	var json = data;
	var content = "";
	for (var i = 0; i < json.length; i++) {
		var name = json[i].name;
		
		var showName = name;
		if(showName.indexOf("\Desktop")!=-1){
			showName = "桌面"
			name = name.split("\\").join("\\\\");
		}
		if(recovery){
			content = content +
			"<li title='"+name+"'><a href='javascript:selectRecoveryPath(\""+name+"/\",\"recovery\")'><p>"+showName+"</p></a></li>";
		}else{
			content = content +
			"<li title='"+name+"'><a href='javascript:selectRecoveryPath(\""+name+"/\")'><p>"+showName+"</p></a></li>";
		}
	}
	$(".w-dir-list ul").html(content);
}
function selectSafeboxPath(path){
	$(".window").css("display","block");
	$(".shadowDiv").css("display","block");
	var abDir = $("#ab-dir").html();
	if(abDir!=""){
		$("#ab-dir").html(abDir+"\\"+path);
		service.getSystemDirs({
			path:abDir+"\\"+path
		}, selectPathCB);
	}else{
		$("#ab-dir").html(path);
		service.getSystemDirs({
			path:path
		}, selectPathCB);
	}
}
function selectParentPath(path){
	var abDir = $("#ab-dir").html();
	var idx = abDir.lastIndexOf("\\");
	if(idx!=-1){
		abDir = abDir.substring(0,idx);
		$("#ab-dir").html(abDir);
    	service.getSystemDirs({
    		path:abDir
    	}, selectPathCB);
	}else{
		$("#ab-dir").html("");
		service.getSystemDirs({
			path:""
		}, selectPathCB);
	}
}

function confirmDir(){
	var h_whichGetModel =  $("#h_whichGetModel").val();
	if(h_whichGetModel == "importDs"){
		importDs();
	}else if(h_whichGetModel == "recovery"){
		var version = $("#h_version").val();
		recovery(version);
	}else{
		plugin.msgtip({type:"e",msg:"参数缺失!"});
	}
}
function cancelDir(){
	clearDateAndWindow();
}

function recovery(version,dynamicCode){
	var dsId = $("#h_dsId").val();
	var path ="/"+$("#h_path").val();
	var abDir = $("#ab-dir").html();
	var nid = $("#h_nid").val();
	if(abDir == ""){
		plugin.msgtip({type:"e",msg:"请选择下载目录"});
		return;
	}
	$("#confirmBtn").css("color","gray");
	service.recoveryFile({
		dsId:dsId,
		rootTreeDsId:$dsId,
		path:encodeURIComponent(path),
		version:version,
		dynamicCode:dynamicCode,
		abDir:encodeURIComponent(abDir),
		nid:nid
	}, recoveryCB);
}

var recoveryCB = function(data){
	$("#confirmBtn").css("color","#fff");
	var json = data;
	var dsId = json.dsId;
	if(json.code=="200" || json.code==200){
		
		clearDateAndWindow();
		
		$("#status"+dsId).html("备份中");
		
		var td_id = $("#h_bartd_id").val();
    	$("#"+td_id).parent().find("td").find(".tipspan").html("等待链接...");
   		var content = ""
   		+"<div style='width:100px;height:20px;border:solid 1px #B8C86C;margin:0 auto;position:relative;'>"
   		+"<div id='processbar' style='width:0px;height:20px;background:#B8C86C;'></div>"
   		+"<div class='r-info' style='position:absolute;top:0;left:0;width:100%;height:20px;'>下载进度:<span id='percentage' style='color:green'>0.00%</span></div>"
   		+"</div>";
   		
   		var td_id = $("#h_bartd_id").val();
   		$("#"+td_id).html(content);
   		
	 }else{
		 dsSecurityRankCheck(json,json.message);
	 }
}

function clearDateAndWindow(){
	$("#dynamicCode").val("");
	$("#ab-dir").html("");
	hideDialog("versionWindow");
	closeCodeWindow();
	$(".window").css("display","none");
	$(".shadowDiv").css("display","none");
}

function setDynamicCode(){
	var dynamicCode = $("#dynamicCode").val();
	if(dynamicCode == ""){
		 plugin.msgtip({type: "e", msg: "动态验证码不能为空!"});
		return;
	}
	var h_whichGetModel = $("#h_whichGetModel").val();
	if(h_whichGetModel=="handBackup"){
		var dsSecurityRank = $("#h_dsSecurityRank").val();
		handBackup($dsId, dsSecurityRank, dynamicCode);
	}else{
		var version = $("#h_version").val();
		recovery(version,dynamicCode);
	}
	
}

function getDownloadProcessBar() {

	var ids = "";
	$(".bartd").each(function() {
		ids += $(this).attr("nid") + ",";
	});
	if (ids.length > 0) {
		ids = ids.substring(0, ids.length - 1);
		service.getDownloadProcessBar({
			nids:ids
		}, processbarCB);
		service.deleteDownloadProcessBar({
			nids:ids
		}, delProcessbarCB,function(data){window.location.href="/web/html/login.html";});
	}
}


var processbarCB = function(data){
	var json = data;
	var list = json.beans;
	for (var i = 0; i < list.length; i++) {
		var bean = list[i];
		$(".bartd").each(function(){
			var nid = $(this).attr("nid");
			if (nid == bean.nid) {
				var count = bean.count;
				var total = bean.total;
				var fileSum = bean.fileSum;
				var okSum = bean.okSum;
				var errorSum = bean.errorSum;
				var percent = (count/total)*100;
				
				var content = ""
			   		+"<div style='width:100px;height:20px;border:solid 1px #B8C86C;margin:0 auto;position:relative;'>"
			   		+"<div id='processbar' style='width:0px;height:20px;background:#B8C86C;'></div>"
			   		+"<div class='r-info' style='position:absolute;top:0;left:0;width:100%;height:20px;'>下载进度:<span id='percentage' style='color:green'>0.00%</span></div>"
			   		+"</div>";
				$(this).html(content);
				
				if(count >= total || (okSum+errorSum)>=fileSum){
					$(this).parent().find("td").find(".tipspan").html("");
					$(this).html("下载完成!");
					if(bean.nid.indexOf('DS-')!=0){ 
						setTimeout(function(){
							$("#j-reset").click();
						}, 3000);
					}
					if(total==0){
						service.deleteDownloadProcessBarByNid({nid:nid}, function(data){;})
					}
				}else if(count == -1 || errorSum==fileSum){
					$(this).find(".r-info").html("<font color='red'>下载失败！</font>");
					service.deleteDownloadProcessBarByNid({
						nid:nid
					}, function(data){;});
				}else{
	    			$(this).parent().find("td").find(".tipspan").html("正在下载...");
	    			$(this).find("#processbar").css("width",percent+"%");
	    			$(this).find("#percentage").html((Math.floor(percent*100)/100)+"%");
				}
			}
		});
	}
}
var delProcessbarCB = function(data) {
	var json = data;
	if(json.code=="200"){
		getVersionTree($dsId, $path, $version, $root, 1);
	}
}


$(function(){
	initTree();
})

function initTree(reload){
	var setting;
	var zNodes =[];
	setting = {
		async: {
            enable: true,
            url: "/rest/datasource/menu",
            autoParam: ["id","type","version","path","dsId","requestType"],
            dataType: "json",
            dataFilter:function(treeId, parentNode, responseData){
            	if(responseData.code == "200"){
            		var nodes = [];
                	getTree(responseData.list,nodes);
                	return nodes;
            	}else{
            		plugin.msgtip({type: "e",msg: responseData.message});
            	}
            },
            type:"get"
        },
        view: {
            fontCss: getFont,
            dblClickExpand: false,
            showLine: false
        },
        data: {
            simpleData: {
                enable: true
            }
        },
        callback: {
            onClick: onClick
        }
    };
	
	service.getMenuTree({type:"0",requestType:"0"},function(json){
		if(json.code == "200"){
			getTree(json.list,zNodes,reload);
			$.fn.zTree.init($("#treeDemo"), setting, zNodes);
			var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
			var terminalNodes = treeObj.getNodesByParam("id", json.list[0].id);
			if (terminalNodes.length>0) {
				treeObj.expandNode(terminalNodes[0], true ,false,true,true);		
			}
		}else{
			plugin.msgtip({type: "e",msg: json.message});
		}
		
	});
}
    
function onClick(e,treeId, treeNode) {
	if(!treeNode.dsId){
		$("#"+treeNode.tId+"_a").removeClass("curSelectedNode");
		return false;
	}
	if(treeNode.root!=undefined && treeNode.root !=""){
		$root = treeNode.root;
	}
	if(treeNode.dsId!=""){
		getVersionTree(treeNode.dsId,treeNode.path,treeNode.version);
	}
}
function getFont(treeId, node) {
    return node.font ? node.font : {};
}
var args = {}; 
function getTree(json,nodes,reload){
	for(var i = 0;i<json.length; i++){
		var data = {};
		data.id = json[i].id;
		data.name = json[i].name;
		data.pId = json[i].pid;
		data.type = (parseInt(json[i].type) + 1)+"";
		data.version = json[i].version;
		data.path = json[i].path;
		data.dsId = json[i].dsId;
		data.requestType = json[i].requestType;
		data.root = json[i].root;
		data.isParent = true;
		if(json[i].type == "0"){
			data.iconSkin = "sty01"
			$dsId = data.dsId;
			$version = data.version;
			$path = data.path;
		}else if(json[i].type == "1"){
			data.iconSkin = "sty02"
		}else{
			data.iconSkin = "sty03"
		}
		nodes[i] = data;
	}
	var root;
	if(data){
		root = data.root;
	}
	if(!reload){
		getVersionTree($dsId,$path,$version,root,1);
	}
}

function createFolder(){
	
	var folderName = $("#folderName").val();
	if(folderName==""){
		plugin.msgtip({type: "e", msg: "文件夹名称不能为空!"});
		return;
	}
	service.createVersionTreeFolder({
		dsId:$dsId,
		version:$version,
		path:$path,
		folderName:folderName
	}, function(data){
		hideDialog("createFolderWindow",false,function(){
			initTree(true);
			getVersionTree($dsId, $path, $version, $root, 1);
		});
	});
}

function nodeReload(){
	getVersionTree($dsId, $path, $version, $root, 1);
}

